import { _decorator, Component, director, EditBox } from 'cc';
import { ApiMsgEnum } from '../Common';
import { SceneEnum } from '../Enum';
import DataManager from '../Global/DataManager';
import { NetworkManager } from '../Global/NetworkManager';
const { ccclass } = _decorator;

@ccclass("LoginManager")
export class LoginManager extends Component {

    input: EditBox
    protected onLoad(): void {
        this.input = this.node.getComponentInChildren(EditBox);
        director.preloadScene(SceneEnum.Hall)
    }

    async start() {
        await this.connectServer();
    }

    async connectServer() {
        if (!(await NetworkManager.Instance.connect().catch(() => false))) {
            await new Promise(res => setTimeout(res, 100))
            await this.connectServer();
        }
    }

    async handleLoginClick() {
        if (!NetworkManager.Instance.isConnected) {
            this.connectServer();
            console.log("网络未连接！开始重连")
            return;
        }
        const nickname = this.input.string;
        if (!nickname) {
            console.log("请输入昵称！")
            return;
        }
        const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiPlayerJoin, { nickname })
        if (!success) {
            console.log(error)
            return;
        }

        DataManager.Instance.myPlayerId = res.player.id;
        console.log("登录成功!", res)

        director.loadScene(SceneEnum.Hall)
    }
}